package com.speedchina.common.message.email.service.impl;
import com.speedchina.common.message.email.entity.Mail;
import com.speedchina.common.message.email.service.MailService;
import com.speedchina.common.message.util.SendResult;
import com.speedchina.common.message.wechat.util.Base64Utils;
import com.speedchina.framework.helper.Assert;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.InputStream;

/**
 * @author zyw
 */
@Service
public class MailServiceImpl  implements MailService{
    @Value("${speedchina.message.mail.username:}")
    private String from;
    @Value("${speedchina.message.mail.to:}")
    private String to;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private TemplateEngine templateEngine;

    public SendResult sendSimpleMail(String to,String cc, String subject, String content) {
        String[] tos = to.split(",");
        String[] ccs =null;
        if(StringUtils.isNotBlank(cc)&&StringUtils.isNotEmpty(cc)){
            cc.split(",");
        }
        for (int i = 0; i < tos.length; i++) {
            this.check(tos[i],subject,content);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(tos[i]);
            message.setSubject(subject);
            message.setText(content);
            if(ccs!=null){
                message.setCc(ccs[i]);
            }
            try {
                mailSender.send(message);
            } catch (Exception e) {
                e.printStackTrace();
                return  new SendResult().SendFail(false,"邮件发送失败"+e.getMessage());
            }
        }
        return  new SendResult().SendSucess(true,"邮件发送成功");
    }

    public SendResult sendSimpleMail(String subject, String content) {
        return this.sendSimpleMail(to,null,subject,content);
    }

    public SendResult sendHtmlMail(String to, String subject, String content) {
        this.check(to,subject,content);
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            return  new SendResult().SendSucess(true,"邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return  new SendResult().SendFail(false,"邮件发送失败");
        }
    }

    public SendResult sendHtmlMail(String[] to, String[] cc, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            if(cc!=null && cc.length!=0){
                helper.setCc(cc);
            }
            mailSender.send(message);
            return  new SendResult().SendSucess(true,"邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return  new SendResult().SendFail(false,"邮件发送失败"+e.getMessage());
        }
    }

    public SendResult sendAttachmentsMail(String to, String subject, String content, String filePath) {
        this.check(to,subject,content);
        MimeMessage message = mailSender.createMimeMessage();
        try {
            InputStream inputStreamByUrl = Base64Utils.getInputStreamByUrl(filePath);
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
            helper.addAttachment(MimeUtility.encodeWord(fileName), new ByteArrayResource(IOUtils.toByteArray(inputStreamByUrl)));
            mailSender.send(message);
            return  new SendResult().SendSucess(true,"邮件发送成功");

        } catch (Exception e) {
            e.printStackTrace();
            return  new SendResult().SendFail(false,"邮件发送失败"+e.getMessage());

        }
    }

    public SendResult sendAttachmentsMail(String to, String subject, String content, String[] filePath) {
        this.check(to,subject,content);
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            for (int i = 0; i < filePath.length; i++) {
                InputStream inputStreamByUrl = Base64Utils.getInputStreamByUrl(filePath[i]);
                String fileName = filePath[i].substring(filePath[i].lastIndexOf(File.separator) + 1);
                helper.addAttachment(MimeUtility.encodeWord(fileName), new ByteArrayResource(IOUtils.toByteArray(inputStreamByUrl)));
            }
            mailSender.send(message);
            return  new SendResult().SendSucess(true,"邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return  new SendResult().SendFail(false,"邮件发送失败"+e.getMessage());
        }
    }

    public SendResult sendThymeleafFormwork(String template,Context context, Mail mail) {
        String emailContent = templateEngine.process(template,context);
        SendResult sendResult = null;
        String[] to = new String[mail.getTo().length];
        if(mail.getCc()!=null){
            sendResult =  this.sendHtmlMail(mail.getTo(),mail.getCc(),"邮件",emailContent);
        } else if(mail.getCc()==null){
            for (int i = 0; i < to.length; i++) {
                to[i] = String.valueOf(mail.getTo()[i]);
            }
            sendResult =  this.sendHtmlMail(to,null,"邮件",emailContent);
        }
        return sendResult;
    }
    public void check(String to,String subject,String content){
        Assert.isEmpty(to,"收件人不能为空");
        //Assert.isEmpty(subject,"主题不能为空");
        Assert.isEmpty(content,"内容不能为空");
    }
}
